package com.ishitong.platform.utils.hibernate;

import org.hibernate.Interceptor;
import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;

/**
 * Hibernate存取拦截器<br>
 * 当系统遇到非utf8编码的数据库时，可通过此拦截器进行转码<br>
 * 但是目前转码采用的方式是取得字符串的byte数组，再转存成16进制字符串形式存储到数据库中。<br>
 * 取出的过程就是反向操作。
 * 
 * @author MarkDong
 * @version 2.0
 * @since 1.0
 */
public class ConvertInterceptor extends EmptyInterceptor implements Interceptor {
	protected Log logger = LogFactory.getLog(getClass());
	private String encoding;

	public ConvertInterceptor(String encoding) {
		this.encoding = encoding;
		logger.debug("初始化字符集转换拦截器，目标字符集是" + encoding);
	}

	@Override
	public boolean onLoad(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
		boolean retValue = false;
		for (int i = 0; i < types.length; i++) {
			Type type = types[i];
			if (type.getReturnedClass().equals(String.class)) {
				String temp = (String) state[i];
				if (temp != null) {
					try {
						byte[] bytes = temp.getBytes(encoding);
						state[i] = new String(bytes, "utf8");
						logger.debug("转码前：" + temp + "|转码后：" + state[i]);
					} catch (UnsupportedEncodingException e) {
						logger.error("转码出现错误");
						state[i] = temp;
					}
					retValue = true;
				}
			}
		}
		return retValue;
	}

	@Override
	public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
		boolean retValue = false;
		for (int i = 0; i < types.length; i++) {
			Type type = types[i];
			if (type.getReturnedClass().equals(String.class)) {
				String temp = (String) state[i];
				if (temp != null) {
					try {
						byte[] bytes = temp.getBytes("utf8");
						state[i] = new String(bytes, encoding);
						logger.debug("转码前：" + temp + "|转码后：" + state[i]);
					} catch (UnsupportedEncodingException e) {
						logger.error("转码出现错误");
						state[i] = temp;
					}
					retValue = true;
				}
			}
		}
		return retValue;
	}
}
